import {createSlice,createAsyncThunk} from "@reduxjs/toolkit"
import {  IUserState } from "./typings";
import {updateUserById} from "../api/user"

interface IUpdateUserPayload {
    userId:string,
    newInfo:object
}

export const updateUserInfoAsync  = createAsyncThunk(
    "user/updateUserInfo",
    async (payload:IUpdateUserPayload,thunkApi) =>{
        await updateUserById(payload.userId,payload.newInfo);
        thunkApi.dispatch(updateUserInfo(payload.newInfo))
    }
)

const userSlice = createSlice({
    name:"user",
    initialState:{
        isLogin:false,
        userInfo:{}
    },
    reducers:{
        initUserInfo:(state:IUserState,{payload})=>{
            state.userInfo = payload;
        },
        changeUserStatus:(state:IUserState,{payload})=>{
            state.isLogin = payload
        },
        // 更新用户信息
        updateUserInfo:(state:IUserState,{payload})=>{
            for(let key in payload){
                (state.userInfo as any)[key] = payload[key];
            }
        },
        clearUserInfo:(state:IUserState,{payload})=>{
            state.userInfo = payload
        }
    },
    extraReducers:(builder)=>{
        // 专门处理异步的reducers
        builder.addCase(updateUserInfoAsync.fulfilled,(state,action)=>{
        })
    }
})
export const {initUserInfo,changeUserStatus,clearUserInfo,updateUserInfo} = userSlice.actions;
export default userSlice.reducer;
